# coding: utf-8

from . import criteria
from numpy import array, sqrt, mean, sum, inf


@criteria
def stop_condition(ctx, source_cloud: array, target_cloud: array, min_err=0.00001, max_delta_err=0.00001,
                   max_iterations=50):
    counter = ctx.get('counter', 0)
    ctx['counter'] = counter + 1
    if counter < max_iterations:
        last_rms = ctx.get('last_rms', inf)
        # calculate current error.
        # rms = mean([sqrt(pow(p - x, 2).sum()) for p, x in zip(source_cloud, target_cloud)])
        rms = mean(sqrt(sum((source_cloud - target_cloud) ** 2, axis=1)))
        ctx['last_rms'] = rms
        if rms < ctx.get('min_rms', inf):
            ctx['min_rms'] = rms
        print("RMS: %f" % rms)
        if rms > 7:
            ctx['not_conv'] = True
            raise RuntimeError
        return rms < min_err or abs(last_rms - rms) < max_delta_err or (
        ctx.get('not_conv', False) and rms <= ctx['min_rms'])
    else:
        return True
